using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using FreeLancer.HRB.Services;
using FreeLancer.HRB.Domains;
using FreeLancer.HRB.Core;
using FreeLancer.HRB.Core.Services;
using DevExpress.Web.Data;
using DevExpress.Web.ASPxGridView;
using System.Threading;
using DevExpress.Web.ASPxEditors;

namespace FreeLancer.HRB.WebApp.Admin.Pages
{
  public partial class Posts : System.Web.UI.Page
  {
    #region Members

    private TList<FreeLancer.HRB.Domains.Posts> _posts;
    private Guid _categoryId = Guid.Empty;
    private int _languageId = 0;

    #endregion

    #region Page Events

    protected void Page_Init(object sender, EventArgs e)
    {
      if (!IsPostBack)
        LoadLanguage();
      
      if (cboLanguage.Items.Count > 0)
        _languageId = int.Parse(cboLanguage.Items[0].Value);
      else
        _languageId = 0;

      if (!IsPostBack)
        LoadCategory();

      if (cboCategory.Items.Count > 0)
        _categoryId = new Guid(cboCategory.Items[0].Value);
      else
        _categoryId = Guid.Empty;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
      InitializeData();
    }

    #endregion

    #region ASPxGridViewPosts Events

    protected void ASPxGridViewPosts_OnHtmlRowPrepared(object sender, ASPxGridViewTableRowEventArgs e)
    {
      if (e.RowType != GridViewRowType.Data) return;
      bool isPublished = Convert.ToBoolean(ASPxGridViewPosts.GetRowValuesByKeyValue(e.KeyValue, "IsPublished"));
      if (!isPublished)
      {
        e.Row.BackColor = System.Drawing.Color.FromArgb(255, 200, 200);
      }
    }

    protected void ASPxGridViewPosts_OnDeleting(object sender, ASPxDataDeletingEventArgs e)
    {
      if (e.Keys["PostId"] != null)
      {
        PostsService postService = GlobalCache.PostServiceInstance;
        PostCommentService postCommentService = GlobalCache.PostCommentServiceInstance;

        Guid id = (Guid)e.Keys["PostId"];

        try
        {
          using (ConnectionScope.CreateTransaction())
          {
            TList<PostComment> postComments = postCommentService.GetByPostId(id);
            postCommentService.Delete(postComments);

            postService.Delete(id);

            InitializeData();

            //Because do not use the SqlDataSource, 
            //so the grid do not have normal delete method.
            //Can handle it by canceling and going back to browser mode.
            e.Cancel = ConnectionScope.Complete();
          }
        }
        catch (Exception ex)
        {
          LoggingService.LogCritical("Admin-Posts Page", "Exception when delete Posts",
              ex, LoggingService.DefaultCategory, true);
        }
      }
    }

    protected void ASPxGridViewPosts_OnUpdating(object sender, ASPxDataUpdatingEventArgs e)
    {
      if (e.Keys["PostId"] != null)
      {
        PostsService postService = GlobalCache.PostServiceInstance;
        Guid id = (Guid)e.Keys["PostId"];

        FreeLancer.HRB.Domains.Posts post = _posts.Find("PostId", id);

        if (post != null)
        {
          post.IsPublished = (bool)e.NewValues["IsPublished"];
          post.IsCommentAllowed = (bool)e.NewValues["IsCommentAllowed"];
          post.Title = e.NewValues["Title"] as string;
          post.Author = e.NewValues["Author"] as string;
          post.DateModified = DateTime.Now;

          try
          {
            using (ConnectionScope.CreateTransaction())
            {
              postService.Save(post);

              InitializeData();

              //Because do not use the SqlDataSource, 
              //so the grid do not have normal update method.
              //Can handle it by canceling and going back to browser mode.
              e.Cancel = ConnectionScope.Complete();
              ASPxGridViewPosts.CancelEdit();
            }
          }
          catch (Exception ex)
          {
            LoggingService.LogCritical("Admin-Posts Page", "Exception when update Posts",
              ex, LoggingService.DefaultCategory, true);
          }
        }
      }
    }

    #endregion

    #region ASPxGridViewComments Events

    protected void ASPxGridViewComments_OnHtmlRowPrepared(object sender, ASPxGridViewTableRowEventArgs e)
    {
      ASPxGridView gridView = sender as ASPxGridView;
      if (gridView != null)
      {
        if (e.RowType != GridViewRowType.Data) return;
        bool isPublished = Convert.ToBoolean(gridView.GetRowValuesByKeyValue(e.KeyValue, "IsApproved"));
        if (!isPublished)
        {
          e.Row.BackColor = System.Drawing.Color.FromArgb(255, 200, 200);
        }
      }
    }

    protected void ASPxGridViewComments_OnBeforePerformDataSelect(object sender, EventArgs e)
    {
      ASPxGridView gridView = sender as ASPxGridView;
      if (gridView != null)
      {
        try
        {
          Guid postId = (Guid)gridView.GetMasterRowKeyValue();
          PostCommentService service = GlobalCache.PostCommentServiceInstance;
          TList<PostComment> postComments = service.GetByPostId(postId);

          gridView.DataSource = postComments;
          gridView.SortBy(gridView.Columns["CommentDate"],
            DevExpress.Data.ColumnSortOrder.Descending);
        }
        catch (Exception ex)
        {
          LoggingService.LogCritical("Admin-Posts Page", "Exception when get PostComment",
            ex, LoggingService.DefaultCategory, true);
        }
      }
    }

    protected void ASPxGridViewComments_OnDeleting(object sender, ASPxDataDeletingEventArgs e)
    {
      if (e.Keys["PostCommentId"] != null)
      {
        PostCommentService postCommentService = GlobalCache.PostCommentServiceInstance;

        Guid id = (Guid)e.Keys["PostCommentId"];

        try
        {
          using (ConnectionScope.CreateTransaction())
          {
            postCommentService.Delete(id);

            InitializeData();

            //Because do not use the SqlDataSource, 
            //so the grid do not have normal delete method.
            //Can handle it by canceling and going back to browser mode.
            e.Cancel = ConnectionScope.Complete();
          }
        }
        catch (Exception ex)
        {
          LoggingService.LogCritical("Admin-Posts Page", "Exception when delete PostComment",
              ex, LoggingService.DefaultCategory, true);
        }
      }
    }

    protected void ASPxGridViewComments_OnUpdating(object sender, ASPxDataUpdatingEventArgs e)
    {
      ASPxGridView gridView = sender as ASPxGridView;
      if ((e.Keys["PostCommentId"] != null) && (gridView != null))
      {
        PostCommentService postCommentService = GlobalCache.PostCommentServiceInstance;
        Guid id = (Guid)e.Keys["PostCommentId"];

        TList<PostComment> postComments =
          (TList<PostComment>)gridView.DataSource;
        PostComment postComment = postComments.Find("PostCommentId", id);

        if (postComment != null)
        {
          postComment.IsApproved = GetIsApproved(gridView);
          postComment.Comment = GetComment(gridView);
          postComment.CommentDate = DateTime.Now;

          try
          {
            using (ConnectionScope.CreateTransaction())
            {
              postCommentService.Save(postComment);

              InitializeData();

              //Because do not use the SqlDataSource, 
              //so the grid do not have normal update method.
              //Can handle it by canceling and going back to browser mode.
              e.Cancel = ConnectionScope.Complete();
              gridView.CancelEdit();
            }
          }
          catch (Exception ex)
          {
            LoggingService.LogCritical("Admin-Posts Page", "Exception when update PostComment",
              ex, LoggingService.DefaultCategory, true);
          }
        }
      }
    }

    protected void ASPxGridViewComments_OnInserting(object sender, ASPxDataInsertingEventArgs e)
    {
      ASPxGridView gridView = sender as ASPxGridView;
      if (gridView != null)
      {
        PostCommentService postCommentService = GlobalCache.PostCommentServiceInstance;
        Guid id = (Guid)gridView.GetMasterRowKeyValue();

        PostComment postComment = new PostComment();

        postComment.PostId = id;
        postComment.IsApproved = GetIsApproved(gridView);
        postComment.Comment = GetComment(gridView);
        postComment.CommentDate = DateTime.Now;
        postComment.Author = Thread.CurrentPrincipal.Identity.Name;

        try
        {
          using (ConnectionScope.CreateTransaction())
          {
            postCommentService.Save(postComment);

            InitializeData();

            //Because do not use the SqlDataSource, 
            //so the grid do not have normal update method.
            //Can handle it by canceling and going back to browser mode.
            e.Cancel = ConnectionScope.Complete();
            gridView.CancelEdit();
          }
        }
        catch (Exception ex)
        {
          LoggingService.LogCritical("Admin-Posts Page", "Exception when insert PostComment",
            ex, LoggingService.DefaultCategory, true);
        }
      }
    }

    #endregion

    #region cboLanguage Events

    protected void cboLanguage_SelectedIndexChanged(object sender, EventArgs e)
    {
    }

    #endregion

    #region cboCategory  Events

    protected void cboCategory_SelectedIndexChanged(object sender, EventArgs e)
    {
    }

    protected void cboCategory_DataBound(object sender, EventArgs e)
    {
      cboCategory.Items.Insert(0, new ListItem(Resources.labels.noneItem, "0"));
    }

    #endregion

    #region Page Processing

    /// <summary>
    /// Initialize language to combobox
    /// </summary>
    private void LoadLanguage()
    {
      int total = 0;
      LanguagesService languageService = new LanguagesService();
      TList<Languages> languages = languageService.GetPaged("IsActive='True'", string.Empty, 0, 3, out total);
      cboLanguage.DataSource = languages;
      cboLanguage.DataTextField = "Name";
      cboLanguage.DataValueField = "LanguageID";
      cboLanguage.DataBind();
    }

    private void LoadCategory()
    {
      int total = 0;
      CategoriesService categoryService = GlobalCache.CategoriesService;
      TList<Categories> categories = //categoryService.GetByLanguageId(_languageId);
        categoryService.GetPaged("LanguageID=" + _languageId +
          "AND CategoryID NOT IN ('2e9e24b0-c419-48ec-91c0-1bdbb43a8500', '792ad48a-3bec-4565-8600-5f9162e4b474')", 
          string.Empty, 0, 100, out total);
      categories.Sort("CategoryName");

      cboCategory.DataSource = categories;
      cboCategory.DataTextField = "CategoryName";
      cboCategory.DataValueField = "CategoryID";
      cboCategory.DataBind();
    }

    /// <summary>
    /// Initialize for GridView Post
    /// </summary>
    private void InitializeData()
    {
      if (!string.IsNullOrEmpty(cboLanguage.SelectedValue))
      {
        _languageId = int.Parse(cboLanguage.SelectedValue);
        if((cboCategory.SelectedIndex >= 0) && (cboCategory.SelectedValue.Length == 36))
          _categoryId = new Guid(cboCategory.SelectedValue);
       
        try
        {
          //Get post by category and language
          PostsService service = GlobalCache.PostServiceInstance;
          _posts = service.GetPostByCategoryIdLanguageIdBE(_categoryId.ToString(), (int?)_languageId);
          ASPxGridViewPosts.DataSource = _posts;
          ASPxGridViewPosts.DataBind();

          ASPxGridViewPosts.SortBy(ASPxGridViewPosts.Columns["DateModified"],
            DevExpress.Data.ColumnSortOrder.Descending);
        }
        catch (Exception ex)
        {
          LoggingService.LogCritical("Admin-Posts Page", "Exception when get Posts",
            ex, LoggingService.DefaultCategory, true);
        }
      }
    }

    #endregion

    #region Helper Methods

    protected string GetComment(ASPxGridView grid)
    {
      ASPxMemo memo = grid.FindEditFormTemplateControl("ASPxMemoComment") as ASPxMemo;
      return memo.Text;
    }

    protected bool GetIsApproved(ASPxGridView grid)
    {
      ASPxCheckBox chkApproved = grid.FindEditFormTemplateControl("ASPxCheckBoxApproved") as ASPxCheckBox;
      return chkApproved.Checked;
    }

    #endregion
  }
}
